package net.huashitong.ssydt.provider.web.utils;

import javax.servlet.http.HttpServletRequest;

/**
 * @author hemj
 * @version 2017/8/10
 */
public class WebUtils {

    /**
     * 返回客户端IP(ip1[,ip2][,ip3])
     */
    public static String getClientIpAddrs(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if ((ip == null) || (ip.length() == 0) || ("unknown".equalsIgnoreCase(ip))) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if ((ip == null) || (ip.length() == 0) || ("unknown".equalsIgnoreCase(ip))) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if ((ip == null) || (ip.length() == 0) || ("unknown".equalsIgnoreCase(ip))) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if ((ip == null) || (ip.length() == 0) || ("unknown".equalsIgnoreCase(ip))) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if ((ip == null) || (ip.length() == 0) || ("unknown".equalsIgnoreCase(ip))) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    /**
     * 返回客户端IP(只返回 getClientIpAddrs 中的第一条IP)
     */
    public static String getClientIpAddr(HttpServletRequest req) {
        String addr = getClientIpAddrs(req);
        if (addr != null) {
            addr = addr.replaceAll(",.+", "");
        }
        return addr;
    }

}
